#!/usr/bin/env python

import os

import sys
if sys.version < '2.3':
    print ("Error: Python version too old. You need at "
           "least Python 2.2 to use this package.")
    print "(you're running version %s)" % sys.version
    sys.exit(0)

# Provide a bunch of custom components that make it possible to build and
# install non-.py files into the package destinations.
from distutils.core import setup
from distutils import dir_util
from distutils.command.build import build as buildcmd
from distutils.command.build_ext import build_ext
from distutils.command.install_lib import install_lib as installcmd
from distutils.dist import Distribution

EXTS = ['.rng', '.rnc', '.txt', '.rst', '.xml']
IGNORE_NAMES = ('CVS', '.svn', 'build', 'dist', 'lib')
ignored = lambda x: filter(None, [x.endswith(n) for n in IGNORE_NAMES])

# This class walks the file system looking for auxiliary files that
# distutils doesn't install properly, and it actually copies those
# files (when hooked into by distutils).
class Finder:

    def __init__(self, exts, prefix):
        self._files = []
        self._exts = exts
        self._plen = len(prefix)

    def visit(self, ignore, dir, files):
        # Remove ignored filenames
        [files.remove(n) for n in files if ignored(n)]
        for file in files:
            # Add any extra files we're interested in
            base, ext = os.path.splitext(file)
            if ext in self._exts:
                self._files.append(os.path.join(dir, file))

    def copy_files(self, cmd, outputbase):
        for file in self._files:
            dest = os.path.join(outputbase, file[self._plen:])
            # Make sure the destination directory exists
            dir = os.path.dirname(dest)
            if not os.path.exists(dir):
                dir_util.mkpath(dir)
            cmd.copy_file(file, dest)

def remove_stale_bytecode(arg, dirname, names):
    names = map(os.path.normcase, names)
    for name in names:
        if name.endswith(".pyc") or name.endswith(".pyo"):
            srcname = name[:-1]
            if srcname not in names:
                fullname = os.path.join(dirname, name)
                print "Removing stale bytecode file", fullname
                os.unlink(fullname)

# Create the finder instance, which will be used in lots of places.  `finder'
# is the global we're most interested in.
base_dir = os.getcwd()
package_dir = os.path.join(os.path.dirname(base_dir), '')
finder = Finder(EXTS, package_dir)
os.path.walk(base_dir, finder.visit, None)

# Distutils hook classes
class MyBuilder(buildcmd):
    def run(self):
        os.path.walk(os.curdir, remove_stale_bytecode, None)
        buildcmd.run(self)
        finder.copy_files(self, self.build_lib)

class MyLibInstaller(installcmd):
    def run(self):
        installcmd.run(self)
        finder.copy_files(self, self.install_dir)

class MyDistribution(Distribution):
    # To control the selection of MyLibInstaller and MyBuilder, we
    # have to set it into the cmdclass instance variable, set in
    # Distribution.__init__().
    def __init__(self, *attrs):
        Distribution.__init__(self, *attrs)
        self.cmdclass['build'] = MyBuilder
        self.cmdclass['install_lib'] = MyLibInstaller

scripts=['scripts/run_lex.py',
        ]

setup(
    name='lex',
    version = '0.1.1' ,
    description = "A simple tokenizer for a algorithm-like language",
    author = "Sidnei da Silva",
    author_email = "sidnei@awkly.org",
    url = "http://awkly.org",
    scripts=scripts,
    package_dir = {
    'lex':'',
    },
    packages=[
    'lex',
    ],
    classifiers = [
        'Development Status :: 4 - Beta',
        'Environment :: Console',
        'License :: OSI Approved :: Python Software Foundation License',
        'Operating System :: POSIX',
        'Operating System :: MacOS :: MacOS X',
        'Operating System :: Microsoft :: Windows :: Windows 95/98/2000',
        'Operating System :: Microsoft :: Windows :: Windows NT/2000',
        'Programming Language :: Python',
        ],
    distclass = MyDistribution,
    )
